package org.hagopa.games.moneypool.game;

import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


import org.hagopa.games.moneypool.dblayer.GameGeneralInfoAdopt;
import org.hagopa.games.moneypool.dblayer.Connector.DBConnector;
import org.hagopa.games.moneypool.dblayer.GameBoardInfoAdopt;
import org.hagopa.games.moneypool.game.gameobjects.Property;
import org.hagopa.games.moneypool.game.gameobjects.PropertyStatusEnum;
import org.hagopa.games.moneypool.msgs.CommandsEnum;
import org.hagopa.games.moneypool.msgs.Message;
import org.hagopa.games.moneypool.msgs.ContentTypes.game.DiesThrow;
import org.hagopa.games.moneypool.msgs.ContentTypes.game.PropertyActionCT;
import org.hagopa.games.moneypool.msgs.ContentTypes.game.StartTurn;
import org.hagopa.games.moneypool.msgs.ContentTypes.game.UpdateStatus;
import org.hagopa.games.moneypool.msgs.ContentTypes.game.UpgradePropCT;
import org.hagopa.games.moneypool.msgs.ContentTypes.game.Ustatus;
import org.hagopa.games.moneypool.msgs.ContentTypes.game.VerificationCT;
import org.hagopa.games.moneypool.msgs.ContentTypes.game.WaitActivePlayer;
import org.hagopa.games.moneypool.msgs.ContentTypes.service.BServMsg;
import org.hagopa.games.moneypool.msgs.ContentTypes.service.JoinResponse;
import org.hagopa.games.moneypool.network.NetClientHandler;
import org.hagopa.games.moneypool.utils.CommonTracer;

public class GameProcedure {

	//This class should be responsible for update Game status from PlayerHolder actions
	// and return status to player for further transfer to client

	private GameGeneralInfoAdopt gameData = null;
	private Bank gameBank = null;
	private GameBoardInfoAdopt locBoard = null;
	private DiesPair localDies = new DiesPair();
	private boolean started = false;
	private ConcurrentHashMap<Integer, PlayerHolder> plh = null;
	private JoinResponse jrContent = new JoinResponse();
	private int activePlayer = 0;
        private CommonTracer cLogger = CommonTracer.getInstance();
        private InterNegotiateState _ins = null;
        private int passBonus = 60;
        private int stayBonus = 100;
	//private UpdateStatus updStatusList = null; //

	public GameProcedure(GameGeneralInfoAdopt gd)
	{
		this.gameData = gd;
                this._ins = new InterNegotiateState();
	}
	public void init()
	{

		//this.locBoard = new Board();
		DBConnector.connect();
                this.gameBank = new Bank((int)this.gameData.getStart_gm_sum(), this.gameData.getStart_payment());
                this.locBoard = new GameBoardInfoAdopt(this.gameData.getGame_id());
                this.locBoard.requestDB();
                //this.locBoard = new Board(DBConnector.getInstance(),this.gameData.getGame_id(), this.gameData.getTemplate_id());


	}


	public void startGame()
	{
		System.out.println("[GameProcedure](startGame) - Starting Game");
		if(this.gameData.getMax_players()== this.plh.size())
		{
			this.started = true;
		}
	}
	public void setupPlayersList(ConcurrentHashMap<Integer, PlayerHolder> plist)
	{
		this.plh = plist;
		if(this.plh == null)
			System.out.println("[GameProcedure](setupPlayersList) - Received  empty players list");
		else
			System.out.println("[GameProcedure](setupPlayersList) - Good players list");
	}

	private void setActivePlayer()
	{
		Random randGen = new Random();

		this.activePlayer = randGen.nextInt(gameData.getMax_players())+ 1;
		if(this.activePlayer > gameData.getMax_players())
			this.activePlayer = gameData.getMax_players();
		System.out.println("[GameProcedure] setActivePlayer - Random Active Index:" + this.activePlayer);
	}
	private void setNextActivePlayer()
	{
		if(activePlayer >= gameData.getMax_players())
		{
			activePlayer = 1;
		}
		else
		{
			activePlayer++;
		}
	}
	public int getActivePlayerInt()
	{
		return activePlayer;
	}

	public  List<UpdateStatus> setupUpdateList()
	{
		List<UpdateStatus> plList = null;
		for(int i = 0; i< gameData.getMax_players(); i++)
		{
			//TODO what?
		}
		return plList;
	}

	private boolean ifallPlayersReady()
	{
		if(this.plh.size() == this.gameData.getMax_players())
		{
			Set <Integer> indexes = this.plh.keySet();

			Iterator<Integer> pit = indexes.iterator();
			while(pit.hasNext())
			{
				Integer ind;
				ind =pit.next();
				System.out.println("Index in game:" + ind);
				if(((PlayerHolder)this.plh.get(ind)).getTurnStatus() != 0)
					return false;
			}
			return true;
		}
		return false;

	}

	private PlayerHolder getActivePLayer()
	{
		//URGENT!!!!!
		PlayerHolder tmpph = this.plh.get(this.activePlayer);
		return tmpph;
	}



	//UPDATE_STATUS record:
	// update_type:181/182
	// new sub status WAIT_ACTIVE_PLAYER = 184
	//(|plid|new_position|cash_status|abid|upgrade_level|curr_cost|fee|status|owner|)
	//
	public void getPlayerAction(PlayerHolder ph)
	{
		//1 - check if player Holder Exists
		//2 - get last msg from player holder
		//3 - Create RespMsg and BCmsg
		//4 - fill both msgs by switch on Commnad
		//5 - send response to Client
		//6 - send broadcast to other clients

		if(null == ph)
			return;
		Message lastmsg = null, respmsg = null, bcmsg = null;
		if(ph.getClientHandler() instanceof NetClientHandler)
		{
			System.out.println("[GameProcedure](getPlayerAction) - Handler of NetClientHandler type");
			lastmsg = ((NetClientHandler)ph.getClientHandler()).getLastClientMsg();
			respmsg = new Message();
                        respmsg.setClientIP(((NetClientHandler)ph.getClientHandler()).getClientIP());
                        respmsg.setHashKey(((NetClientHandler)ph.getClientHandler()).getHashKey());
			bcmsg = new Message();
                        bcmsg.setClientIP(((NetClientHandler)ph.getClientHandler()).getClientIP());
                        bcmsg.setHashKey(((NetClientHandler)ph.getClientHandler()).getHashKey());
		}
		else
		{
			System.out.println("[GameProcedure](getPlayerAction) - Unknown Client Handler Type");
			return;
		}


                String servMsg = new String();
                int type;
                String logmsg;
                PropertyActionCT pac;
                
		switch(lastmsg.getCommand())
		{
			case READY:
                                servMsg = "Player " +ph.getName() + " has entered the room";
                                type = 0;
                                this.ServBroadcastSend(type, ((NetClientHandler)ph.getClientHandler()).getClientId(),servMsg);
//                                try {
//                                     Thread.sleep(300);
//                                 } catch (InterruptedException ex) {
//                                    Logger.getLogger(GameProcedure.class.getName()).log(Level.SEVERE, null, ex);
//                                 }
                                logmsg = " READY command";
                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
                                bcmsg.setCommand(CommandsEnum.JOIN_RESPONSE);
                                jrContent.pushNewRecord(((NetClientHandler)ph.getClientHandler()).getClientId(), ph.getName());
                                System.out.println("[GameProcedure](getPlayerAction) num of Joined players:" + jrContent.getNumOfElements());
                                bcmsg.setContentHandler(jrContent);
                                System.out.println("[GameProcedure](getPlayerAction) size of update content: " + jrContent.getSize());
                                bcmsg.setContentSz(jrContent.getSize());//TODO@!!!!
                                jrContent.printallrecords();
                                broadcastSend(bcmsg, false);


				break;
                        case START_GAME:

				ph.setTurnStatus(0);

                                servMsg = "Player " +ph.getName() + " has joined the game";
                                type = 1;
                                logmsg = " START_GAME command";
                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
				if(ifallPlayersReady() == true)
				{
                                    this.ServBroadcastSend(type,((NetClientHandler)ph.getClientHandler()).getClientId(),servMsg);

                                    respmsg.setCommand(CommandsEnum.UPDATE);
                                    bcmsg.setCommand(CommandsEnum.UPDATE);
                                    System.out.println("[GameProcedure](getPlayerAction) - all player are ready");
                                    setActivePlayer();
                                    PlayerHolder acpl = getActivePLayer();
                                    servMsg = "Player " +acpl.getName() + " starts turn";
                                    type = 0;
                                    this.ServBroadcastSend(type, (((NetClientHandler)acpl.getClientHandler()).getClientId()),servMsg);
                                    if(acpl == null)
                                    {
                                            System.out.println("[GameProcedure](getPlayerAction) - Failed to get active player");
                                            return;
                                    }
                                    respmsg.setClientId(((NetClientHandler)acpl.getClientHandler()).getClientId());
                                    respmsg.setSessionId(((NetClientHandler)acpl.getClientHandler()).getSessionId());
                                    respmsg.setCommand(CommandsEnum.UPDATE);
                                    StartTurn st = new StartTurn();

                                    respmsg.setContentSz(4);
                                    respmsg.setContentHandler(st);
                                    ((NetClientHandler)acpl.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)acpl.getClientHandler()).sendMsg(respmsg.marshall());

                                    System.out.println("\n-------[GameProcedure](getPlayerAction) - sent PLAY command to active player!\n" );
                                    WaitActivePlayer wap = new WaitActivePlayer();
                                    wap.setActiveClientId(((NetClientHandler)acpl.getClientHandler()).getClientId());

                                    bcmsg.setContentHandler(wap);
                                    bcmsg.setContentSz(wap.getSize());
                                    broadcastSend(bcmsg, true);

				}
                                break;
			case AC_NONE:
				bcmsg.setCommand(CommandsEnum.UPDATE);
				break;

			case AC_BUY:
                            //TODO: Check if property owned by other player, and if yes, was fee paid
				// Must be all checking actions: If player allowed to buy property, if he has money, if this property is for sale and soon.
                                pac = ((PropertyActionCT)((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getContentHandler());
                                respmsg = ac_buy_prepare(ph);
                                logmsg = " AC_BUY command";
                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
                                if(respmsg != null)
                                {
                                    System.out.println("\n========================\nSending resp on AC_BUY\n");
                                    ((NetClientHandler)ph.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)ph.getClientHandler()).sendMsg(respmsg.marshall());
                                    bcmsg = ac_buy_bc_prepare(ph);

                                    broadcastSend(bcmsg, false);
                                    String plname;
                                    if(pac.getPartnerCID()!= 0)
                                    {
                                        PlayerHolder lph = plh.get(pac.getPartnerCID());
                                        plname = lph.getName();
                                    }
                                    else
                                    {
                                        plname = "Bank";
                                    }
                                    servMsg = "Player " + ph.getName()
                                            + " wants to buy " + locBoard.getFieldById(pac.getFieldId()).getName()
                                            + "from " + plname  + "for sum " + pac.getDealSum();
                                    type = 0;
                                    this.ServBroadcastSend(type, ((NetClientHandler)ph.getClientHandler()).getClientId(),servMsg);
                                }
				break;

			case AC_SELL:
                             //TODO: Check if property owned by player

                                respmsg = ac_sell_prepare(ph);
                                logmsg = " AC_SELL command";
                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
                                if(respmsg != null)
                                {
                                    System.out.println("\n========================\nSending resp on AC_SELL\n");
                                    ((NetClientHandler)ph.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)ph.getClientHandler()).sendMsg(respmsg.marshall());
                                    bcmsg = ac_sell_bc_prepare(ph);
                                    if(null != bcmsg)
                                    {
                                        broadcastSend(bcmsg, false);
                                    }
                                    else
                                    {
                                        System.out.println("[GameProcedure](getPlayerAction)/AC_SELL/ failed to create broadcast msg");
                                    }
                                    pac = ((PropertyActionCT)((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getContentHandler());
                                    servMsg = "Player " +ph.getName() + " wants to sell  " +
                                          this.locBoard.getFieldById(pac.getFieldId()).getName() +
                                        "To Player " + pac.getPartnerCID() + "for sum " + pac.getDealSum();
                                    type = 0;
                                    this.ServBroadcastSend(type, ((NetClientHandler)ph.getClientHandler()).getClientId(),servMsg);
                                }
				break;
			case AC_PAY:
                                pac = ((PropertyActionCT)((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getContentHandler());
                                
                                respmsg = ac_pay_prepare(ph);
                                if(respmsg != null)
                                {
                                    logmsg = " AC_PAY command: Pay sum:"  + pac.getDealSum();
                                    cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
                                    ((NetClientHandler)ph.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)ph.getClientHandler()).sendMsg(respmsg.marshall());
                                    bcmsg.setCommand(CommandsEnum.UPDATE);
                                    bcmsg = ac_pay_bc_prepare(ph);
                                    broadcastSend(bcmsg, false);
                                    servMsg = "Player " +ph.getName() + " pays fee " +
                                        pac.getDealSum() + ", for visiting on " + this.locBoard.getFieldById(pac.getFieldId()).getName() +
                                        "To Player " + pac.getPartnerCID();
                                    type = 0;
                                    this.ServBroadcastSend(type, ((NetClientHandler)ph.getClientHandler()).getClientId(),servMsg);
                                }
				break;
			case AC_MORTGAGE:
                            //TODO: Check if property owned by player
                                respmsg = ac_mortgage_prepare(ph);
                                if(respmsg != null)
                                {
                                    System.out.println("\n========================\nSending resp on AC_MORTGAGE\n");
                                    ((NetClientHandler)ph.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)ph.getClientHandler()).sendMsg(respmsg.marshall());
                                    bcmsg = ac_mortgage_bc_prepare(ph);
                                    broadcastSend(bcmsg, false);
                                }
				break;
			case AC_EXCHANGE:
                                System.out.println("\n========================\nAC_EXCHANGE   [NOT IMPLEMENTED]\n");
//                                logmsg = " AC_EXCHANGE command";
//                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
//				bcmsg.setCommand(CommandsEnum.UPDATE);
				break;
                        case AC_UPGRADE:
                                logmsg = " AC_UPGRADE command";
                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
                                respmsg = ac_upgrade_prepare(ph);
                                if(respmsg != null)
                                {
                                    ((NetClientHandler)ph.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)ph.getClientHandler()).sendMsg(respmsg.marshall());
                                    bcmsg = ac_upgrade_bc_prepare(ph);
                                    broadcastSend(bcmsg, false);
                                }
                                break;
                        case NG_AC_BUY:
                                logmsg = " Buy Action negotiation command";
                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
                                respmsg = ng_buy_resp_prep(ph);
                                if(respmsg != null)
                                {
                                    System.out.println("\n========================\nSending resp on AC_BUY\n");
                                    System.out.println("to: " + respmsg.getClientId() +"\n");
                                    PlayerHolder opponent = this.plh.get(respmsg.getClientId());
                                    ((NetClientHandler)opponent.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)opponent.getClientHandler()).sendMsg(respmsg.marshall());
                                    bcmsg = ac_buy_bc_prepare(opponent);
                                    if(null != bcmsg)
                                    {
                                        broadcastSend(bcmsg, false);
                                    }
                                    else
                                    {
                                        System.out.println("[GameProcedure](getPlayerAction)/AC_SELL/ failed to create broadcast msg");
                                    }
                                }
                                break;
                        case NG_AC_EXCHANGE:
                                System.out.println("\n========================\nReceived Event  NG_AC_EXCHANGE\n");
                                logmsg = " Exchange Action negotiation command";
                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
                                break;
                        case NG_AC_SELL:
                                System.out.println("\n========================\nReceived Event  NG_AC_SELL from CID"+
                                        ((NetClientHandler)ph.getClientHandler()).getClientIP()+"\n");

                                respmsg = ng_sell_resp_prep(ph);
                                if(respmsg != null)
                                {
                                    System.out.println("\n========================\nSending resp on AC_SELL\n");
                                    System.out.println("to: " + respmsg.getClientId() +"\n");
                                    PlayerHolder opponent = this.plh.get(respmsg.getClientId());
                                    ((NetClientHandler)opponent.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)opponent.getClientHandler()).sendMsg(respmsg.marshall());
                                    bcmsg = ac_sell_bc_prepare(opponent);
                                    if(null != bcmsg)
                                    {
                                        broadcastSend(bcmsg, false);
                                    }
                                    else
                                    {
                                        System.out.println("[GameProcedure](getPlayerAction)/AC_SELL/ failed to create broadcast msg");
                                    }
                                }
                                break;
                        case GET_QUEST:
                                // should response to client with Quest action
                                break;
			case THR_DIES:
				System.out.println("\n========================\nSending resp on THR_DIES\n");
				respmsg = throw_dies(ph);
				((NetClientHandler)ph.getClientHandler()).setMsg4Client(respmsg);

				((NetClientHandler)ph.getClientHandler()).sendMsg(respmsg.marshall());
				bcmsg.setCommand(CommandsEnum.UPDATE);
				bcmsg.setContentSz(respmsg.getContentSz());
				bcmsg.setContentHandler(respmsg.getContentHandler());
				broadcastSend(bcmsg, true);
				break;
			case MOVE_DONE:
                                logmsg = " Move Done Event";
                                cLogger.storeLogmsg(1, this.gameData.getGame_id(), ((NetClientHandler)ph.getClientHandler()).getClientId(), 0 , logmsg);
                                respmsg = move_done_resp(ph);
                                ((NetClientHandler)ph.getClientHandler()).setMsg4Client(respmsg);
				((NetClientHandler)ph.getClientHandler()).sendMsg(respmsg.marshall());
				bcmsg.setCommand(CommandsEnum.UPDATE);
                                servMsg = "Player " +ph.getName() + " moved to field ";
                                type = 0;
                                this.ServBroadcastSend(type, ((NetClientHandler)ph.getClientHandler()).getClientId(),servMsg);
				break;
			case END_TURN:
				//recalculate next active player
                                PlayerHolder acpl = getActivePLayer();
                                if(((NetClientHandler)acpl.getClientHandler()).getClientId() == ((NetClientHandler)ph.getClientHandler()).getClientId())
                                {
                                    setNextActivePlayer();
                                    acpl = getActivePLayer();
                                    servMsg = "Player " +acpl.getName() + " starts turn";
                                    type = 0;
                                    this.ServBroadcastSend(type, (((NetClientHandler)acpl.getClientHandler()).getClientId()),servMsg);
                                    if(acpl == null)
                                    {
                                            System.out.println("[GameProcedure](getPlayerAction) - Failed to get active player");
                                            return;
                                    }
                                    respmsg.setClientId(((NetClientHandler)acpl.getClientHandler()).getClientId());
                                    respmsg.setSessionId(((NetClientHandler)acpl.getClientHandler()).getSessionId());
                                    respmsg.setCommand(CommandsEnum.UPDATE);
                                    StartTurn st = new StartTurn();

                                    respmsg.setContentSz(4);
                                    respmsg.setContentHandler(st);
                                    ((NetClientHandler)acpl.getClientHandler()).setMsg4Client(respmsg);
                                    ((NetClientHandler)acpl.getClientHandler()).sendMsg(respmsg.marshall());

                                    System.out.println("\n-------[GameProcedure](getPlayerAction) - sent PLAY command to active player!\n-------" );
                                    WaitActivePlayer wap = new WaitActivePlayer();
                                    wap.setActiveClientId(((NetClientHandler)acpl.getClientHandler()).getClientId());
                                    bcmsg.setCommand(CommandsEnum.UPDATE);
                                    bcmsg.setContentHandler(wap);
                                    bcmsg.setContentSz(wap.getSize());
                                    //and send broadcast to all players
                                    broadcastSend(bcmsg, true);
                                }
//                                if(create_update_bc_content(bcmsg))
//                                {
//                                    broadcastSend(bcmsg, true);
//                                }

				// and UPDATE + 181 to active player
				break;
			case DISCONNECT:
				System.out.println("Disconnecting");
				break;
			default:
				((NetClientHandler)ph.getClientHandler()).response();
					break;
		}
	}


	public void broadcastSend(Message msg , boolean flag)//if flag false - means send to all clients, even to active player !!!
	{
		System.out.println("[GameProcedure](broadcastSend) - Broadcasting :" + msg.getCommand().getName() + "[" + msg.getCommand().idx() + "]");
		System.out.println("[GameProcedure](broadcastSend) - Broadcasting flag = " + flag);
		Set <Integer> indexes = this.plh.keySet();

		Iterator<Integer> pit = indexes.iterator();
		while(pit.hasNext())
		{

			Integer pid = pit.next();
			System.out.println("[GameProcedure](broadcastSend) - PlayerId:" + pid);
			System.out.println("[GameProcedure](broadcastSend) - Active Player:" + this.activePlayer);
			if(flag && pid.equals(new Integer(this.activePlayer)))
			{
				System.out.println(" [GameProcedure](broadcastSend) - Skipping....");
				continue;
			}
			PlayerHolder tmp = this.plh.get(pid);

			msg.setClientId(((NetClientHandler)tmp.getClientHandler()).getClientId());

			msg.setSessionId(((NetClientHandler)tmp.getClientHandler()).getSessionId());

			((NetClientHandler)tmp.getClientHandler()).sendMsg(msg.marshall());
		}
	}
        public void ServBroadcastSend(int type, int cid, String msg )
	{
                Message bmsg = new Message();
                bmsg.setCommand(CommandsEnum.SERV_BROADCAST);

		System.out.println("[GameProcedure](ServBroadcastSend) - Broadcasting :"
                                    + bmsg.getCommand().getName() + "[" + bmsg.getCommand().idx() + "]");

                BServMsg mcnt = new BServMsg();
                mcnt.setSenderId(cid);
                mcnt.setType(type);
                mcnt.setMsg(msg);
                mcnt.setTotal_size(msg.length());

                int gid = (int)this.gameData.getGame_id();
                mcnt.setSenderId(gid);
                bmsg.setContentHandler(mcnt); //should create msg content

		Set <Integer> indexes = this.plh.keySet();

		Iterator<Integer> pit = indexes.iterator();
		while(pit.hasNext())
		{

			Integer pid = pit.next();
			System.out.println("[GameProcedure](ServBroadcastSend) - PlayerId:" + pid);

			PlayerHolder tmp = this.plh.get(pid);

			bmsg.setClientId(((NetClientHandler)tmp.getClientHandler()).getClientId());
			bmsg.setSessionId(((NetClientHandler)tmp.getClientHandler()).getSessionId());

			((NetClientHandler)tmp.getClientHandler()).sendMsg(bmsg.marshall());
		}
	}

	public boolean isStarted() {
		return started;
	}
        private Message move_done_resp(PlayerHolder ph)
        {
            Message lmsg = new Message();
            lmsg.setCommand(CommandsEnum.MOVE_DONE);
            VerificationCT verContent = new VerificationCT();
            verContent.setOKCode();
            lmsg.setContentHandler(verContent);
            lmsg.setContentSz(verContent.getSize());
            lmsg.setClientId(((NetClientHandler)ph.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)ph.getClientHandler()).getSessionId());
            return lmsg;
        }
        
	private Message throw_dies(PlayerHolder ph)
        {
            Message lmsg = new Message();
            lmsg.setCommand(CommandsEnum.UPDATE);

            DiesThrow dthr = new DiesThrow();
            this.localDies.generateNewThrow();

            dthr.setFirst(this.localDies.getFirstD());
            dthr.setSecond(this.localDies.getSeconfD());
            dthr.setAcid(((NetClientHandler)ph.getClientHandler()).getClientId());
            int newpos = 0;
            int offset = 1;
            //next cases : currpos = x, newpos = x+y where x+y < board_size
            //             currpos = x, newpos = x+y where x+y = board_size+1
            //             currpos = x, newpos = x+y where x+y > board_size+1
            int suppose_pos = ph.getCurrPosition() + (this.localDies.getFirstD()+ this.localDies.getSeconfD());
            if((suppose_pos) > this.gameData.getBoard_sz())
            {
                if(suppose_pos == (this.gameData.getBoard_sz() + 1))
                {
                    ph.setCash(ph.getCash() + stayBonus);
                }
                else
                {
                    ph.setCash(ph.getCash() + passBonus);
                }
                newpos = suppose_pos - this.gameData.getBoard_sz();
            }
            else
            {
                newpos = suppose_pos;
            }
            ph.setCurrPosition(newpos, offset);

            lmsg.setClientId(((NetClientHandler)ph.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)ph.getClientHandler()).getSessionId());
            lmsg.setContentSz(dthr.getSize());
            lmsg.setContentHandler(dthr);
            return lmsg;
        }
	private Message ac_sell_prepare(PlayerHolder ph)
        {
            if(ph == null)
            {
                System.out.println("[GameProcedure](ac_sell_prepare) epmty PlayerHolder");
                return null;
            }
            Message lmsg = new Message();
            PropertyActionCT pact = null;
            PropertyActionCT outpact = null;
            VerificationCT verContent = new VerificationCT();
            
            Message lastmsg = ((NetClientHandler)ph.getClientHandler()).getLastClientMsg();
            if(lastmsg == null)
            {
                System.out.println("[GameProcedure](ac_sell_prepare) epmty lastmsg");
                return null;
            }
            pact = (PropertyActionCT)lastmsg.getContentHandler();
            if(null == pact)
            {
                System.out.println("[GameProcedure](ac_sell_prepare) epmty property action");
                return null;
            }
            if(pact.getFieldId() > this.gameData.getBoard_sz())
            {
                System.out.println("[GameProcedure](ac_sell_prepare) Undefined index of property!! (out of board size)");
                lmsg.setCommand(CommandsEnum.AC_SELL);
                verContent.setErr(ErrorsEnum.UNDEFINED_PROP_IND);
            }
            else
            {
                if(pact.getPartnerCID() == 0)
                {
               
                    ph.setCash(ph.getCash() + pact.getDealSum());
                    ph.printStatus();
                    this.locBoard.getFieldById(pact.getPartnerCID()).setOwner(((NetClientHandler)ph.getClientHandler()).getClientId());
                    lmsg.setCommand(CommandsEnum.AC_SELL);
                    verContent.setOKCode();
                }
                else
                {
                    PlayerHolder oppph = this.plh.get(pact.getPartnerCID());
                    if(oppph == null)
                    {
                        System.out.println("[GameProcedure](ac_sell_prepare) Invalid CID");
                        return null;
                    }
                    lmsg.setCommand(CommandsEnum.NG_AC_SELL);
                    this._ins.setDealType(DealTypes.DSELL);
                    this._ins.setOpponent(pact.getPartnerCID());
                    this._ins.setInitiator(((NetClientHandler)ph.getClientHandler()).getClientId());
                    this._ins.setDealSum(pact.getDealSum());
                    this._ins.setDealProperty(pact.getFieldId());
                    this._ins.printState();
                    lmsg.setClientId(((NetClientHandler)oppph.getClientHandler()).getClientId());
                    lmsg.setSessionId(((NetClientHandler)oppph.getClientHandler()).getSessionId());
                    outpact = new PropertyActionCT();
                    outpact.setFieldId(pact.getFieldId());
                    outpact.setDealSum(pact.getDealSum());
                    outpact.setPartnerCID(((NetClientHandler)ph.getClientHandler()).getClientId());
                    lmsg.setContentSz(outpact.getSize());
                    lmsg.setContentHandler(outpact);
                    ((NetClientHandler)oppph.getClientHandler()).setMsg4Client(lmsg);
                    ((NetClientHandler)oppph.getClientHandler()).sendMsg(lmsg.marshall());
                    return null;
                }
            }
            lmsg.setClientId(((NetClientHandler)ph.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)ph.getClientHandler()).getSessionId());

            lmsg.setContentSz(verContent.getSize());
            lmsg.setContentHandler(verContent);
            return lmsg;
        }
        private Message ng_sell_resp_prep(PlayerHolder ph)
        {
            if(ph == null)
            {
                System.out.println("[GameProcedure](ng_sell_resp_prep) epmty PlayerHolder");
                return null;
            }
            Message lmsg = new Message();
            VerificationCT veresp = (VerificationCT)((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getContentHandler();
            System.out.println("[GameProcedure](ng_sell_resp_prep) Initiator:" + this._ins.getInitiator());
            PlayerHolder opponent = this.plh.get(this._ins.getInitiator());
            if(opponent == null)
            {
                return null;
            }

            lmsg.setClientId(((NetClientHandler)opponent.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)opponent.getClientHandler()).getSessionId());

            if(veresp.getErr() == 0)
            {
                System.out.println("[GameProcedure](ng_sell_resp_prep) Deal is accepted");
                Property actprop = this.locBoard.getFieldById(_ins.getDealProperty());
                actprop.setOwner(((NetClientHandler)ph.getClientHandler()).getClientId());
                this._ins.printState();
                ph.setCash(ph.getCash() - _ins.getDealSum());
                
                opponent.setCash(opponent.getCash() + _ins.getDealSum());
            }
            else
            {
                System.out.println("[GameProcedure](ng_sell_resp_prep) Deal is rejected");
            }
            lmsg.setCommand(CommandsEnum.AC_SELL);
            lmsg.setContentSz(veresp.getSize());
            lmsg.setContentHandler(veresp);

            return lmsg;
        }

        private Message ng_buy_resp_prep(PlayerHolder ph)
        {
            if(ph == null)
            {
                System.out.println("[GameProcedure](ng_buy_resp_prep) epmty PlayerHolder");
                return null;
            }
            Message lmsg = new Message();
            
            VerificationCT veresp = (VerificationCT)((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getContentHandler();
            PlayerHolder opponent = this.plh.get(this._ins.getInitiator());
            if(opponent == null)
            {
                return null;
            }

            lmsg.setClientId(((NetClientHandler)opponent.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)opponent.getClientHandler()).getSessionId());

            if(veresp.getErr() == 0)
            {
                System.out.println("[GameProcedure](ng_buy_resp_prep) Deal is accepted");
                Property actprop = this.locBoard.getFieldById(_ins.getDealProperty());
                actprop.setOwner(_ins.getInitiator());
                ph.setCash(ph.getCash() + _ins.getDealSum());
                
                opponent.setCash(opponent.getCash() - _ins.getDealSum());
                
            }
            else
            {
                System.out.println("[GameProcedure](ng_buy_resp_prep) Deal is rejected");
            }
            lmsg.setCommand(CommandsEnum.AC_BUY);
            lmsg.setContentSz(veresp.getSize());
            lmsg.setContentHandler(veresp);

            return lmsg;
        }
        private Message ac_sell_bc_prepare(PlayerHolder ph)
        {
            if(ph == null)
            {
                System.out.println("[GameProcedure](ac_sell_bc_prepare) epmty PlayerHolder");
                return null;
            }
            Message lmsg = new Message();
            lmsg.setCommand(CommandsEnum.UPDATE);
            PropertyActionCT pact = null;
            Message lastmsg = ((NetClientHandler)ph.getClientHandler()).getMsg4Client();
            UpdateStatus us = new UpdateStatus();
            Set<Integer> plids = this.plh.keySet();
            Iterator<Integer> itr = plids.iterator();
            int updated_property;
            String objname = lastmsg.getClass().getName();
            System.out.println("(ac_sell_bc_prepare) - Content type name:" + objname);
            if(lastmsg.getCommand() == CommandsEnum.AC_SELL)
            {
                updated_property = this._ins.getDealProperty();
            }
            else
            {
                pact = (PropertyActionCT)lastmsg.getContentHandler();
                updated_property = pact.getFieldId();
            }
            us.setAbId(updated_property);
            us.setFee(this.locBoard.getFieldById(updated_property).getFee());
            us.setCurrentCost(this.locBoard.getFieldById(updated_property).getCurrCost());
            us.setUpgradeLevel(this.locBoard.getFieldById(updated_property).getUpgradeLevel());
            us.setStatus(this.locBoard.getFieldById(updated_property).getStatus());
            us.setOwner(this.locBoard.getFieldById(updated_property).getOwner());
            while(itr.hasNext())
            {
                PlayerHolder tpl = this.plh.get(itr.next());
                Ustatus tmp = new Ustatus();
                System.out.println("[GameProcedure](ac_sell_bc_prepare) Another player: "+ ((NetClientHandler)tpl.getClientHandler()).getClientId());
                tmp.setPlayerId(((NetClientHandler)tpl.getClientHandler()).getClientId());
                tmp.setPlayerName(tpl.getName());
                tmp.setPlayerPosition(tpl.getCurrPosition());
                tmp.setPlayerCash(tpl.getCash());
                tmp.showStatus();
                us.addRecord(tmp);//DEBUG

            }
            lmsg.setCommand(CommandsEnum.UPDATE);
            lmsg.setContentHandler(us);
            System.out.println("[GameProcedure](ac_sell_bc_prepare) - content size:" + us.getSize());
            lmsg.setContentSz(us.getSize());

            return lmsg;
        }
        private Message ac_pay_prepare(PlayerHolder ph)
        {
            if(ph == null)
            {
                System.out.println("[GameProcedure](ac_pay_prepare) epmty PlayerHolder");
                return null;
            }
            Message lmsg = new Message();
            PropertyActionCT pact = null;

            VerificationCT verContent = new VerificationCT();

            Message lastmsg = ((NetClientHandler)ph.getClientHandler()).getLastClientMsg();
            if(lastmsg == null)
            {
                System.out.println("[GameProcedure](ac_sell_prepare) epmty lastmsg");
                return null;
            }
            pact = (PropertyActionCT)lastmsg.getContentHandler();
            if(null == pact)
            {
                System.out.println("[GameProcedure](ac_sell_prepare) epmty property action");
                return null;
            }
            
            ph.printStatus();
            
            

            if(pact.getFieldId() > this.gameData.getBoard_sz())
            {
                System.out.println("[GameProcedure](ac_pay_prepare) Undefined index of property!! (out of board size)");
                lmsg.setCommand(CommandsEnum.DENY);
                verContent.setErr(ErrorsEnum.UNDEFINED_PROP_IND);
                return null;
            }
            else if(this.locBoard.getFieldById(pact.getFieldId()).getStatus() == PropertyStatusEnum.MORGAGED)
            {
                System.out.println("[GameProcedure](ac_pay_prepare) Status of property is Mortgaged!! (Cannot buy)");
                lmsg.setCommand(CommandsEnum.DENY);
                verContent.setErr(ErrorsEnum.NO_PROPERTY);
                return null;
            }
            else if(pact.getDealSum() >= ph.getCash())
            {
                System.out.println("[GameProcedure](ac_pay_prepare) Sum of Deal greater than player has!! (Cannot pay)");
                lmsg.setCommand(CommandsEnum.DENY);
                verContent.setErr(ErrorsEnum.NO_MONEY);
                return null;
            }
            else
            {
                
                ph.setCash(ph.getCash() - pact.getDealSum());
                PlayerHolder lowner = this.plh.get(locBoard.getFieldById(pact.getFieldId()).getOwner());
                lowner.setCash(lowner.getCash() + pact.getDealSum());

                lmsg.setCommand(((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getCommand());
                verContent.setOKCode();
            }
            lmsg.setClientId(((NetClientHandler)ph.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)ph.getClientHandler()).getSessionId());

            lmsg.setContentSz(verContent.getSize());
            lmsg.setContentHandler(verContent);
            return lmsg;
        }
        private Message ac_pay_bc_prepare(PlayerHolder ph)
        {
            if(ph == null)
            {
                System.out.println("[GameProcedure](ac_pay_bc_prepare) epmty PlayerHolder");
                return null;
            }
            Message lmsg = new Message();
            lmsg.setCommand(((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getCommand());
            UpdateStatus us = new UpdateStatus();
            Set<Integer> plids = this.plh.keySet();
            Iterator<Integer> itr = plids.iterator();

            int updated_property = ((PropertyActionCT)((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getContentHandler()).getFieldId();
            us.setAbId(updated_property);
            us.setFee(this.locBoard.getFieldById(updated_property).getFee());
            us.setCurrentCost(this.locBoard.getFieldById(updated_property).getCurrCost());
            us.setUpgradeLevel(this.locBoard.getFieldById(updated_property).getUpgradeLevel());
            us.setStatus(this.locBoard.getFieldById(updated_property).getStatus());
            us.setOwner(this.locBoard.getFieldById(updated_property).getOwner());
            while(itr.hasNext())
            {
                PlayerHolder tpl = this.plh.get(itr.next());
                Ustatus tmp = new Ustatus();

                tmp.setPlayerId(((NetClientHandler)tpl.getClientHandler()).getClientId());
                tmp.setPlayerName(tpl.getName());
                tmp.setPlayerPosition(tpl.getCurrPosition());
                tmp.setPlayerCash(tpl.getCash());
                //plus broadcast to all other clients with update
               // tmp.setStatus(PropertyStatusEnum.FREE_TO_BUY);
                tmp.showStatus();
                us.addRecord(tmp);
            }
            lmsg.setCommand(CommandsEnum.UPDATE);
            lmsg.setContentHandler(us);
            System.out.println("[GameProcedure](getPlayerAction) - content size:" + us.getSize());
            //lmsg.setContentSz(us.getSize());
            return lmsg;
        }
        private Message ac_mortgage_prepare(PlayerHolder ph)
        {
            Message lmsg = new Message();
            PropertyActionCT pact = null;
            if(ph == null)
            {
                System.out.println("[GameProcedure](ac_mortgage_prepare) epmty PlayerHolder");
                return null;
            }
            VerificationCT verContent = new VerificationCT();
            Message lastmsg = ((NetClientHandler)ph.getClientHandler()).getLastClientMsg();
            pact = (PropertyActionCT)lastmsg.getContentHandler();
            if(pact.getFieldId() > this.gameData.getBoard_sz())
            {
                System.out.println("[GameProcedure](ac_mortgage_prepare) Undefined index of property!! (out of board size)");
                lmsg.setCommand(CommandsEnum.DENY);
                verContent.setErr(ErrorsEnum.UNDEFINED_PROP_IND);
            }
            else
            {
                lmsg.setCommand(CommandsEnum.ACCEPT);
                verContent.setOKCode();
            }
            lmsg.setClientId(((NetClientHandler)ph.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)ph.getClientHandler()).getSessionId());

            lmsg.setContentSz(verContent.getSize());
            lmsg.setContentHandler(verContent);
            return lmsg;
        }
        private Message ac_buy_prepare(PlayerHolder ph)
        {
            Message lmsg = new Message();
            PropertyActionCT pact = null;
            PropertyActionCT outpact = null;
            VerificationCT verContent = new VerificationCT();

            ph.printStatus();
            Message lastmsg = ((NetClientHandler)ph.getClientHandler()).getLastClientMsg();
            pact = (PropertyActionCT)lastmsg.getContentHandler();
            String objname = lastmsg.getClass().getName();
            System.out.println("Content type name:" + objname);

            if(pact.getFieldId() > this.gameData.getBoard_sz())
            {
                System.out.println("[GameProcedure](ac_buy_prepare) Undefined index of property!! (out of board size)");
                lmsg.setCommand(CommandsEnum.DENY);
                verContent.setErr(ErrorsEnum.UNDEFINED_PROP_IND);
                return null;
            }
            else if(this.locBoard.getFieldById(pact.getFieldId()).getStatus() == PropertyStatusEnum.MORGAGED)
            {
                System.out.println("[GameProcedure](ac_buy_prepare) Status of property is Mortgaged!! (Cannot buy)");
                lmsg.setCommand(CommandsEnum.DENY);
                verContent.setErr(ErrorsEnum.NO_PROPERTY);
                return null;
            }
            else if(pact.getDealSum() >= ph.getCash())
            {
                System.out.println("[GameProcedure](ac_buy_prepare) Sum of Deal greater than player has!! (Cannot buy)");
                lmsg.setCommand(CommandsEnum.DENY);
                verContent.setErr(ErrorsEnum.NO_MONEY);
                return null;
            }
            else
            {
                this._ins.setDealType(DealTypes.DBUY);
                this._ins.setOpponent(pact.getPartnerCID());
                this._ins.setInitiator(((NetClientHandler)ph.getClientHandler()).getClientId());
                this._ins.setDealSum(pact.getDealSum());
                this._ins.setDealProperty(pact.getFieldId());
                this._ins.printState();
                if(pact.getPartnerCID() == 0)
                {

                    ph.setCash(ph.getCash() - pact.getDealSum());
                    ph.printStatus();
                    this.locBoard.getFieldById(pact.getFieldId()).setOwner(((NetClientHandler)ph.getClientHandler()).getClientId());
                    this.locBoard.getFieldById(pact.getFieldId()).setStatus(PropertyStatusEnum.OWNED_BY_ONE);
                    lmsg.setCommand(CommandsEnum.AC_BUY);
                    verContent.setOKCode();
                }
                else
                {
                    PlayerHolder oppph = this.plh.get(pact.getPartnerCID());
                    if(oppph == null)
                    {
                        System.out.println("[GameProcedure](ac_buy_prepare) Invalid CID");
                        return null;
                    }
                    lmsg.setCommand(CommandsEnum.NG_AC_BUY);
                    
                    lmsg.setClientId(((NetClientHandler)oppph.getClientHandler()).getClientId());
                    lmsg.setSessionId(((NetClientHandler)oppph.getClientHandler()).getSessionId());
                    outpact = new PropertyActionCT();
                    outpact.setFieldId(pact.getFieldId());
                    outpact.setDealSum(pact.getDealSum());
                    outpact.setPartnerCID(((NetClientHandler)ph.getClientHandler()).getClientId());
                    lmsg.setContentSz(outpact.getSize());
                    lmsg.setContentHandler(outpact);
                    ((NetClientHandler)oppph.getClientHandler()).setMsg4Client(lmsg);
                    ((NetClientHandler)oppph.getClientHandler()).sendMsg(lmsg.marshall());
                    return null;
                }
                
                
            }
            lmsg.setClientId(((NetClientHandler)ph.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)ph.getClientHandler()).getSessionId());

            lmsg.setContentSz(verContent.getSize());
            lmsg.setContentHandler(verContent);
            return lmsg;
        }
        private Message ac_buy_bc_prepare(PlayerHolder ph)
        {
            Message lmsg = new Message();
            lmsg.setCommand(((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getCommand());
            UpdateStatus us = new UpdateStatus();
            Set<Integer> plids = this.plh.keySet();
            Iterator<Integer> itr = plids.iterator();
            int updated_property = this._ins.getDealProperty();
            
            us.setAbId(updated_property);
            us.setFee(this.locBoard.getFieldById(updated_property).getFee());
            us.setCurrentCost(this.locBoard.getFieldById(updated_property).getCurrCost());
            us.setUpgradeLevel(this.locBoard.getFieldById(updated_property).getUpgradeLevel());
            us.setStatus(this.locBoard.getFieldById(updated_property).getStatus());
            us.setOwner(this.locBoard.getFieldById(updated_property).getOwner());
            while(itr.hasNext())
            {
                PlayerHolder tpl = this.plh.get(itr.next());
                Ustatus tmp = new Ustatus();

                tmp.setPlayerId(((NetClientHandler)tpl.getClientHandler()).getClientId());
                tmp.setPlayerName(tpl.getName());
                tmp.setPlayerPosition(tpl.getCurrPosition());
                tmp.setPlayerCash(tpl.getCash());
                //plus broadcast to all other clients with update
               // tmp.setStatus(PropertyStatusEnum.FREE_TO_BUY);
                tmp.showStatus();
                us.addRecord(tmp);
            }
            lmsg.setCommand(CommandsEnum.UPDATE);
            lmsg.setContentHandler(us);
            System.out.println("[GameProcedure](getPlayerAction) - content size:" + us.getSize());
            //lmsg.setContentSz(us.getSize());
            return lmsg;
        }
        private Message ac_upgrade_prepare(PlayerHolder ph)
        {
            Message lmsg = new Message();
            
            UpgradePropCT upct = null;
            VerificationCT verContent = new VerificationCT();
            Message lastmsg = ((NetClientHandler)ph.getClientHandler()).getLastClientMsg();
            upct = (UpgradePropCT)lastmsg.getContentHandler();
            lmsg.setCommand(CommandsEnum.AC_UPGRADE);
            if(upct.getFieldId() > this.gameData.getBoard_sz())
            {
                System.out.println("[GameProcedure](ac_upgrade_prepare) Undefined index of property!! (out of board size)");
                
                verContent.setErr(ErrorsEnum.UNDEFINED_PROP_IND);
            }
            else if(this.locBoard.getFieldById(upct.getFieldId()).getStatus() == PropertyStatusEnum.MORGAGED)
            {
                System.out.println("[GameProcedure](ac_upgrade_prepare) Status of property is Mortgaged!! (Cannot buy)");
                
                verContent.setErr(ErrorsEnum.NO_PROPERTY);
                return null;
            }
            else if(this.locBoard.getFieldById(upct.getFieldId()).getOwner() != ((NetClientHandler)ph.getClientHandler()).getClientId())
            {
                System.out.println("[GameProcedure](ac_upgrade_prepare) User not owner of property! Upgrade action not allowed");
                return null;
            }
            else
            {
                if(ifupgradeAllowed(upct.getFieldId()))
                {
                    int lvlDiff = upct.getUpgradeLvl() - this.locBoard.getFieldById(upct.getFieldId()).getUpgradeLevel();
                    int cost = this.locBoard.getFieldById(upct.getFieldId()).getCurrCost();
                    if(lvlDiff > 0)
                    {
                        System.out.println("[GameProcedure](ac_upgrade_prepare) Increase Upgrade Level to :" + upct.getUpgradeLvl());
                        ph.setCash(ph.getCash() - (cost/100*25));
                        this.locBoard.getFieldById(upct.getFieldId()).setCurrCost(cost + (cost/100*25));
                        this.locBoard.getFieldById(upct.getFieldId()).setUpgradeLevel(upct.getUpgradeLvl());

                    }
                    else if(lvlDiff < 0)
                    {
                        System.out.println("[GameProcedure](ac_upgrade_prepare) Decrease Upgrade Level to :" + upct.getUpgradeLvl());
                        ph.setCash(ph.getCash() + (this.locBoard.getFieldById(upct.getFieldId()).getCurrCost()/100*25));
                        this.locBoard.getFieldById(upct.getFieldId()).setUpgradeLevel(upct.getUpgradeLvl());
                    }
                    lmsg.setCommand(CommandsEnum.AC_UPGRADE);
                    verContent.setOKCode();
                }
            }
            lmsg.setClientId(((NetClientHandler)ph.getClientHandler()).getClientId());
            lmsg.setSessionId(((NetClientHandler)ph.getClientHandler()).getSessionId());

            lmsg.setContentSz(verContent.getSize());
            lmsg.setContentHandler(verContent);
            return lmsg;
        }
        private boolean ifupgradeAllowed(int fieldId)
        {
            int currGroupId = this.locBoard.getFieldById(fieldId).getGroup();
            int owner = this.locBoard.getFieldById(fieldId).getOwner();
            List<Property> group = this.locBoard.getFieldsByGroup(currGroupId);
            Iterator <Property> itr = group.iterator();
            while(itr.hasNext())
            {
                if(owner != itr.next().getOwner())
                    return false;
            }
            return true;
        }
        private Message ac_upgrade_bc_prepare(PlayerHolder ph)
        {
            Message lmsg = new Message();
            lmsg.setCommand(CommandsEnum.UPDATE);
            UpdateStatus us = new UpdateStatus();
            int updated_property = ((UpgradePropCT)((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getContentHandler()).getFieldId();
            us.setAbId(updated_property);
            us.setFee(this.locBoard.getFieldById(updated_property).getFee());
            us.setCurrentCost(this.locBoard.getFieldById(updated_property).getCurrCost());
            us.setUpgradeLevel(this.locBoard.getFieldById(updated_property).getUpgradeLevel());
            us.setStatus(this.locBoard.getFieldById(updated_property).getStatus());
            us.setOwner(this.locBoard.getFieldById(updated_property).getOwner());
            Set<Integer> plids = this.plh.keySet();
            Iterator<Integer> itr = plids.iterator();

            while(itr.hasNext())
            {
                PlayerHolder tpl = this.plh.get(itr.next());
                Ustatus tmp = new Ustatus();

                tmp.setPlayerId(((NetClientHandler)tpl.getClientHandler()).getClientId());
                tmp.setPlayerName(tpl.getName());
                tmp.setPlayerPosition(tpl.getCurrPosition());
                tmp.setPlayerCash(tpl.getCash());
                //plus broadcast to all other clients with update
               // tmp.setStatus(PropertyStatusEnum.FREE_TO_BUY);
                tmp.showStatus();
                us.addRecord(tmp);
            }
            lmsg.setCommand(CommandsEnum.UPDATE);
            lmsg.setContentHandler(us);
            System.out.println("[GameProcedure](ac_upgrade_bc_prepare) - content size:" + us.getSize());
            lmsg.setContentSz(us.getSize());
            return lmsg;
        }
        private Message ac_mortgage_bc_prepare(PlayerHolder ph)
        {
            Message lmsg = new Message();
            lmsg.setCommand(CommandsEnum.UPDATE);
            UpdateStatus us = new UpdateStatus();
            int updated_property = ((PropertyActionCT)((NetClientHandler)ph.getClientHandler()).getLastClientMsg().getContentHandler()).getFieldId();
            us.setAbId(updated_property);
            us.setFee(this.locBoard.getFieldById(updated_property).getFee());
            us.setCurrentCost(this.locBoard.getFieldById(updated_property).getCurrCost());
            us.setUpgradeLevel(this.locBoard.getFieldById(updated_property).getUpgradeLevel());
            us.setStatus(this.locBoard.getFieldById(updated_property).getStatus());
            us.setOwner(this.locBoard.getFieldById(updated_property).getOwner());
            Set<Integer> plids = this.plh.keySet();
            Iterator<Integer> itr = plids.iterator();

            while(itr.hasNext())
            {
                PlayerHolder tpl = this.plh.get(itr.next());
                Ustatus tmp = new Ustatus();

                tmp.setPlayerId(((NetClientHandler)tpl.getClientHandler()).getClientId());
                tmp.setPlayerName(tpl.getName());
                tmp.setPlayerPosition(tpl.getCurrPosition());
                tmp.setPlayerCash(tpl.getCash());
                //plus broadcast to all other clients with update
               // tmp.setStatus(PropertyStatusEnum.FREE_TO_BUY);
                tmp.showStatus();
                us.addRecord(tmp);
            }
            lmsg.setCommand(CommandsEnum.UPDATE);
            lmsg.setContentHandler(us);
            System.out.println("[GameProcedure](getPlayerAction) - content size:" + us.getSize());
            lmsg.setContentSz(us.getSize());
            return lmsg;
        }


}
